package org.sockettest.server;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class Main implements Runnable  {
    private static boolean exitFlag = false;
    private static final int port = 11212;
    public static void main(String[] args) {
        new Thread(new Main()).start();
        UserManager userManager = new UserManager();
        try(ServerSocket serverSocket = new ServerSocket(port)){

            System.out.println("聊天室开启");
            while (!exitFlag){
                Socket socket = serverSocket.accept();
                System.out.println("User " + socket.getPort());
                Thread t = new Thread(new ServerThread(socket, userManager));
                t.start();
            }
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            userManager.DelAllUser();
        }

    }

    public static void closeClient(){
        exitFlag = true;
        try {
            new Socket("127.0.0.1", port).close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        try (Scanner scanner = new Scanner(System.in)){
            while (true){
                String s = scanner.nextLine();
                if("exit".equals(s)){
                    closeClient();
                    break;
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
